<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
  {
    style: {
      navigationBarTitleText: '新增地址',
      "enablePullDownRefresh": false,
    },
  }
  </route>
<template>
  <view>
    <view class="m-4">
      <view>
        <wd-form ref="formRef" :model="model" :rules="rules">
          <wd-cell-group>
            <wd-input label="收货人" label-width="100px" prop="contact" clearable v-model="model.contact"
              placeholder="请输入收货人" />
            <wd-input label="联系电话" label-width="100px" prop="mobile" clearable v-model="model.mobile"
              placeholder="请输入联系电话" :maxlength="11" />

            <wd-col-picker prop="province_id" placeholder="请选择地址" label="地址" v-model="city" :columns="area"
              :column-change="columnChange" @confirm="handleConfirmArea"></wd-col-picker>

            <wd-textarea prop="address" label="详细地址" v-model="model.address" placeholder="请输入详细地址" auto-height />

            <view class="flex items-center py-[20rpx] px-[30rpx]">
              <text class="w-[100px] text-sm mr-[30rpx]">默认地址</text>
              <wd-switch v-model="model.is_default" size="20" active-value="1" inactive-value="0" />
            </view>
          </wd-cell-group>

        </wd-form>
      </view>

      <view class="mt-10">
        <wd-button type="primary" block :round="false" @click="handleSubmit">提交</wd-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { useColPickerData } from '@/hooks/useColPickerData'
const { colPickerData, findChildrenByCode } = useColPickerData()
import { fetchCityId, addAddress, editAddress, fetchAddress } from "@/service/address";
import { showToast } from '@/utils/uni';
const formRef = ref();
const model = reactive({
  contact: "",
  mobile: "",
  address: "",
  province_id: "",
  city_id: "",
  district_id: "",
  is_default: 0
});
const city = ref([]);

const area = computed(() => {
  const list = [colPickerData.map((item) => {
    return {
      value: item.value,
      label: item.text
    }
  })]

  if (model.province_id) {
    list.push(findChildrenByCode(colPickerData, model.province_id).map((item) => {
      return {
        value: item.value,
        label: item.text
      }
    }))
  }

  if (model.city_id) {
    list.push(findChildrenByCode(colPickerData, model.city_id).map((item) => {
      return {
        value: item.value,
        label: item.text
      }
    }))
  }

  return list
})
let addressId = "";

const rules = {
  contact: [{ required: true, message: '请输入收货人' }],
  mobile: [{ required: true, message: '请输入联系电话' }],
  province_id: [{ required: true, message: '请选择地址' }],
}




function getAddress() {
  fetchAddress(addressId).then(res => {
    const { province_id, city_id, district_id } = res.data;
    city.value = [province_id, city_id, district_id].map(String);
    Object.keys(res.data).forEach(key => {
      model[key] = String(res.data[key])
    })
  })
}

const columnChange = ({ selectedItem, resolve, finish }) => {
  const areaData = findChildrenByCode(colPickerData, selectedItem.value)
  if (areaData && areaData.length) {
    resolve(
      areaData.map((item) => {
        return {
          value: item.value,
          label: item.text
        }
      })
    )
  } else {
    finish()
  }
}

function handleConfirmArea({ selectedItems, value }) {
  const [province, city, district] = selectedItems.map(item => item.label);
  const [province_id, city_id, district_id] = value;
  model.province_id = province_id;
  model.city_id = city_id;
  model.district_id = district_id;
  // fetchCityId({
  //   province, city, district
  // }).then((res) => {
  //   console.log(res, "????");

  // })
  console.log(province, city, district, value)
}

function handleAction(requestApi) {
  let params = { ...model }
  if (addressId) params.id = addressId;
  requestApi(params).then(res => {
    showToast(addressId ? "更新成功" : "添加成功", uni.navigateBack);
  })
}


function handleSubmit() {
  formRef.value
    .validate()
    .then(({ valid, errors }) => {
      console.log(valid, "???");
      handleAction(addressId ? editAddress : addAddress)
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}
onLoad((options) => {
  addressId = options.id || "";
  if (addressId) {
    uni.setNavigationBarTitle({
      title: "编辑地址"
    })
    getAddress();
  }

})
</script>

<style lang="scss" scoped></style>
